<template>
    <div class="header-message">
        <i class="header-message-icon" :unread="unRead">
            <img src="@/assets/images/notice/notice-icon.png" alt="">
        </i>
        <!-- 小弹窗 -->
        <div class="header-message-main">
            <div class="header-message-poper">
                <ul>
                    <li v-for="item in sortList.slice(0, 3)" :key="item.id" :class="{ readed: item.readed }"
                        @click="openDetail(item)">
                        <h3 v-text="item.title"></h3>
                        <p v-text="item.describe"></p>
                    </li>
                </ul>
                <button v-show="sortList.length > 3" @click="noticeList = true">More</button>
            </div>
        </div>

        <!-- 列表 -->
        <UxDialog class="dialog-responsive" title="Notifications" :visible="noticeList" @close="noticeList = false">

            <div class="notice-list">
                <!-- <el-select v-model="type" size="mini">
                    <el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.label"></el-option>
                </el-select> -->

                <h2>{{ list.length }} messages in total</h2>
                <ul>
                    <li v-for="item in sortList" :key="item.id" :class="{ readed: item.readed }"
                        @click="openDetail(item)">
                        <h3 v-text="item.title"></h3>
                        <article v-html="item.describe || item.content"></article>
                    </li>
                </ul>
            </div>
        </UxDialog>

        <!-- 详情 -->
        <UxDialog class="notice-detail dialog-responsive" :title="(noticeDetail || {}).title" :visible="noticeDetail"
                  :can-close="false">
            <div class="notice-detail-close" @click="detailClose()"><i class="iconfont icon-guanbi"></i></div>
            <div class="notice-detail-content" v-if="noticeDetail">
                <!-- <h2 v-text="noticeDetail.title"></h2> -->
                <article v-html="noticeDetail.content"></article>
                <footer>
                    <span @click="detailClose(e => (noticeList = true))">Return to notification list</span>
                </footer>
            </div>
        </UxDialog>

    </div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
    name: "HeaderbarNotice",
    data () {
        return {
            destroyed: false,
            noticeList: false,
            noticeDetail: null,
            list: [
                // id 不能重复，特别是弹窗的情况下，要用日期做id
                // readed 是否已读
                // force 是否强制弹窗，是否每次启后期都强制弹窗，多个强制弹窗情况下，要都关闭后才回到首页

                // { id: 1708332837907, readed: false, force: true, title: 'Notice of Operational Resumption and Production Delays', describe: 'The entire PODpartner team has resumed normal operations after the Chinese New Year Festival.', content: '<p><strong>Dear Valued User,</strong></p><p>&nbsp;</p><p>We\'re thrilled to share that the entire PODpartner team is back in full swing. As the pioneering factory in China that powered through the Chinese New Year Festival without a break, we\'ve attracted a wave of new users who\'ve switched from other suppliers. However, during the Festival, our factory\'s production capacity was only at 50% (still enough for our regular order volume). The unexpected surge in orders unfortunately led to some delays in production, and for that, we sincerely apologize. But fear not, our factory is now operating at 100% capacity and we\'re committed to clearing all backlog orders within the next five business days. If you\'ve experienced delays during this period, please don\'t hesitate to reach out to our customer service department for compensation. For details, please refer to <a href="https://www.podpartner.com/document/help-center?classify=9&detail=204&page=2" target="_blank">https://www.podpartner.com/document/help-center?classify=9&detail=204&page=2</a>.</p><p>Once again, we extend our heartfelt thanks for your unwavering support and understanding!</p><p>&nbsp;</p><p>Warm regards,</p><p>The PODpartner Team</p>' },
                // { id: 1706598925406, readed: false, force: true, title: 'Holiday Notice', describe: 'Chinese New Year from Feb 10, 2024 until Feb 17, 2024.', content: '<p><strong>Dear Valued User,</strong></p><p>&nbsp;</p><p>We are pleased to inform you that through our diligent efforts and while still ensuring the rest and welfare of our employees our POD factories have achieved uninterrupted year-round operation. We can maintain normal production levels and shipping speeds even during the Chinese New Year holiday. However it is still worth noting that the transportation time may be slightly extended due to the festival holiday beyond our control. Here are the specific details, please take note:</p><p>For orders paid between February 7th and February 15th (GMT+8), the transportation time will be extended as follows:</p><p>Standard Shipping: Up to 2 working days</p><p>Fast Shipping: Up to 2 working days</p><p>Express shipping: Up to 8 working days (If you want to receive the samples as soon as possible, we recommend using our fast shipping.)</p><p>In addition, our dedicated customer service team will be available to address your questions quickly, with responses within 12 hours.</p><p>We wish you a prosperous year in 2024.</p><p>Thank you for your understanding and continued support.</p><p>&nbsp;</p><p>Best regards,</p><p>The PODpartner Team</p>' },
                // { id: 1702542990189, readed: false, force: true, title: 'Notice of potential delay', describe: 'Possibility of 2-3 days delay for the upcoming Holiday.', content: '<p>Dear valued user:</p><p>&nbsp;</p><p>We regret to inform you that due to the peak season and the upcoming holidays, there may be a delay of <strong>2-3 business days</strong> in the local dispatching service. We apologize for any inconvenience this may cause. </p><p>Thank you kindly for your understanding and support. </p><p>&nbsp;</p><p>The PODpartner Team</p><p>2023/12/14</p>' },
                // { id: 1673433062897, readed: false, force: true, title: 'Holiday Notice', describe: 'Chinese New Year from Jan 21, 2023 until Jan 27, 2023.', content: '<p>Holiday Notice</p><br/><p>Dear valued user,</p><br/><p>We would like to inform you that PODpartner will celebrate the Chinese New Year from Jan 21, 2023 until Jan 27, 2023. We assure you that our fulfillment process will be resumed as soon as we return to work. Our online customer service will remain in touch during the holidays and gladly answer your questions within 24 hours. </p><p>Thank you for your continued support. </p><br/><p>Happy year of the rabbit!</p><p>The PODpartner team</p>' },
                // { id: 1671453262528, readed: false, force: true, title: 'Notice of potential delay', describe: 'Due to the relaxation of Covid control measures in China', content: '<p>Dear user, </p><br/><p>Due to the relaxation of Covid control measures in China, Covid cases have been surging in recent weeks. The situation is having a major impact on manufacturing and logistics activities nationwide. Therefore, we expect a delay of around 5 business days in delivering our products. In the meantime, we are going to great lengths to bring our order delivery back to normal. </p><br/><p>We sincerely apologize for any inconvenience this may cause you. Please reach out to our customer support team if you are experiencing a serious delivery delay, and we will do our best to find you a solution.</p><br/><p>Thank you kindly for your understanding and support.</p><br/><p>The PODpartner team </p><p>2022/12/19</p>' },
                // { id: 1695195523726, readed: false, force: true, title: 'Holiday Notice', describe: 'Important update regarding upcoming celebrations', content: '<p>Dear valued user,</p><p>&nbsp;</p><p>As China\'s National Day and Mid-Autumn Festival approach, we wanted to extend a friendly reminder. In this festive season, our printing facility may experience a minor delay of 1-2 business days compared to our standard order duration. Our dedicated customer service team will be available to address your inquiries promptly, with responses within 24 hours.</p><p>&nbsp;</p><p>Kindly note the impacted period: September 29th to October 5th (GMT+8). Only the orders placed and paid for during this time frame may encounter a slight delay in production and shipping.</p><p>&nbsp;</p><p>Your understanding during this holiday period is greatly appreciated.</p><p>&nbsp;</p><p>Warm regards,</p><p>&nbsp;</p><p>The PODpartner Team</p>' },
                { id: 1, readed: true, force: false, title: 'Welcome message', describe: 'Thank you for choosing PODpartner !', content: '<p><strong>Thank you, {{name}}, for choosing PODpartner ！</strong></p><p>We are thrilled that you signed up with us. Let\'s set out to grow your clothing business together!</p><p>&nbsp;</p><p><strong>What we offer</strong></p><p>- An extensive catalog covering a vast array of trendy clothing styles</p><p>- 100% premium cotton garments with consistent availability</p><p>- A powerful design tool allowing up to 18 print areas per garment</p><p>- An in-house factory where 98% of the orders can be fulfilled within 48 hours</p><p>- Efficiency-oriented order processing solutions tailored to your needs</p><p>&nbsp;</p><p>Click <a target="_blank" href="/document/how-work">here</a> to learn how it works.</p><p>&nbsp;</p><p>Sincerely,</p><p>The PODpartner Team</p>' },

            ]
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        unRead () {
            return this.list.filter(item => !item.readed).length > 0
        },
        sortList () {
            //对list进行排序
            let list = this.list;
            let readed = []; //已读
            let unread = []; //未读
            list.map(item => {
                if (item.readed) {
                    readed.push(item)
                } else {
                    unread.push(item)
                }
            })
            unread = unread.sort((a, b) => b.id - a.id);
            return [...unread, ...readed]
        }
    },
    watch: {
        userInfo: {
            deep: true,
            immediate: true,
            handler () {
                const name = (this.userInfo || {}).name || 'user'
                this.list.map(item => {
                    if (item.cacheContent) {
                        item.content = item.cacheContent.replace(/\{\{name\}\}/gi, name);
                    } else {
                        item.cacheContent = item.content;
                        item.content = item.cacheContent.replace(/\{\{name\}\}/gi, name);
                    }
                })
            }
        }
    },
    methods: {

        // 关闭
        close () {
            this.noticeList = false;
            this.noticeDetail = null;
        },

        // 获取已读id
        getRead () {
            const result = []
            try {
                const config = JSON.parse(localStorage.getItem("CONFIG") || '{}');
                config.notice && result.push(...config.notice);
            } catch (e) {
                // 错误
                console.log(e)
            }
            return result;
        },

        // 添加已读
        addRead (item) {
            item.readed = true;
            try {
                const config = JSON.parse(localStorage.getItem("CONFIG") || '{}');
                config.notice = (config.notice || []).filter(i => i != item.id);
                config.notice.push(item.id);
                localStorage.setItem("CONFIG", JSON.stringify(config));
            } catch (e) {
                // 错误
                // console.log(e)
            }
        },

        // 根据用户来提醒
        addItemByUser () {

            if (this.userInfo.special_popup == 2) {
                this.list.unshift({ id: 1720074359941, readed: false, force: true, title: 'Urgent notice', describe: 'Temporary PayPal Payment Gateway Issue.', content: "<p><strong>Dear users,</strong></p><p>&nbsp;</p><p>As of 4:00 PM PST on July 1st, we've encountered technical issues with our PayPal payment gateway, preventing us from processing payments through PayPal. We're actively working with PayPal to resolve this promptly. Meanwhile, please use alternative payment methods to complete your orders.</p><p>&nbsp;</p><p>This issue may be due to increased orders following the launch of our new embroidery service on June 30th. PayPal has not yet provided a clear explanation for the outage.</p><p>&nbsp;</p><p>Our partnership with PayPal has maintained a strong reputation, with a customer complaint rate consistently below 0.1%. This reflects our dedication to delivering high-quality products and excellent service. We're committed to expanding our print-on-demand services to give you more design freedom and support your business growth.</p><p>&nbsp;</p><p>We apologize for any inconvenience caused and are here to help with any questions you may have.</p><p>&nbsp;</p><p>Sincerely,<br/>The PODpartner Team</p>" })
                this.list.unshift({ id: 1721120421873, readed: false, force: true, title: 'PayPal Payment Issue Update', describe: 'Temporary disruption and new payment option coming soon.', content: "<p><strong>Dear users,</strong></p><p>&nbsp;</p><p>Over the past two weeks, we have been actively working with PayPal to address disruptions to our PayPal receiving function. During this time, we have been continuously urging PayPal to resolve the problem, but the teams in China and the United States have been passing the responsibility back and forth, resulting in no resolution or explanation for the issue. We are shocked and disappointed by this situation.</p><p>&nbsp;</p><p>We have been working with PayPal for a long time, maintaining an exemplary complaint rate of less than 0.1% while paying a high transaction fee of 4.4% + USD 0.3 per transaction. However, PayPal\'s inefficiency and irresponsibility in addressing this issue make it impossible for us to continue trusting their service and ensuring they can provide our users with stable service.</p><p>&nbsp;</p><p>We hope this problem is due to the inaction of certain PayPal employees. We are currently making efforts to establish contact with PayPal\'s senior management to seek a clear and prompt resolution.</p><p>&nbsp;</p><p>At the same time, we are establishing a partnership with Payoneer to offer you a superior payment experience. The good news is that Payoneer offers significantly lower transaction fees than PayPal, and we will pass these savings on to you to reduce your payment costs and increase your sales profits.</p><p>&nbsp;</p><p>If you encounter any issues during this period, please do not hesitate to contact our customer service team. They are dedicated to providing you with the best possible support.</p><p>&nbsp;</p><p>Sincerely,<br/>The PODpartner Team</p>" })
            }

        },


        // 打开详情
        openDetail (item) {
            this.isRead = true;
            this.noticeList = false;
            this.noticeDetail = item;
            this.addRead(item)
        },
        detailClose (callback) {

            if (!this.noticeDetail) {
                // 没有显示，不管
            } else {
                const force = this.list.find(i => i.force && !i.readed);
                if (force) {

                    this.openDetail(force)
                } else {
                    this.noticeDetail = null;
                    callback && callback();
                }
            }
        },
        //跳转
        Jump (path) {
            this.$router.push({ path: path });
        },
    },
    mounted () {
        // 如果有打开过
        const reads = this.getRead()

        this.addItemByUser()
        // 如果没有id，表示没有读过
        this.list.map(item => item.readed = item.readed || reads.indexOf(item.id) >= 0);

        // 第一个默认已读
        const force = this.list.find(i => i.force && !i.readed);

        // 强制弹窗
        // 要处理登录后，页面跳转的情况
        if (force && this.$route.path != '/designer') {
            this.isRead = true;
            this.noticeList = false;
            this.noticeDetail = force;
            // 延迟2秒处理
            setTimeout(() => !this.destroyed && this.addRead(force), 2000);
        }

    },
    beforeDestroy () {
        this.destroyed = true;
    }
};
</script>
<style lang="scss" scoped>
.header-message {
    .header-message-icon {
        position: absolute;
        left: 50%;
        top: 50%;
        width: 28px;
        height: 28px;
        border-radius: 28px;
        margin-left: -14px;
        margin-top: -14px;
        text-align: center;
        color: #9d9d9d;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: all 0.2s;

        img {
            width: 20px;
            height: 20px;
        }

        &:hover {
            background-color: rgba(0, 0, 0, 0.06);
        }

        &[unread]::after {
            content: '';
            display: block;
            width: 6px;
            height: 6px;
            background: #f44336;
            border-radius: 4px;
            position: absolute;
            top: 2px;
            right: 2px;
        }
    }

    .header-message-main {
        display: block;
        width: 20vw;
        min-width: 320px;
        position: absolute;
        top: 100%;
        right: 0;
        margin-top: 6px;
        opacity: 0;
        pointer-events: none;
        transition: all 0.2s;

        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 6px;
            margin-top: -6px;
        }
    }

    &:hover {
        &>.header-message-icon {
            color: #ea4c89;
        }

        &>.header-message-main {
            opacity: 1;
            pointer-events: all;
        }
    }
}

.header-message-poper {
    box-sizing: border-box;
    width: 100%;
    padding: 10px 0;
    background: #ffffff;
    box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.12);
    border-radius: 6px;
    border: 1px solid #d9d9d9;

    li {
        &.readed {
            * {
                color: #919191 !important;
            }

            >p::before {
                display: none;
            }
        }

        &:hover {
            background: #f6f6f6;
        }

        &:last-child {
            border-bottom: none;
        }

        cursor: pointer;
        box-sizing: border-box;
        padding: 16px 0;
        line-height: normal;
        width: 100%;
        border-bottom: 1px;
        font-size: 14px;

        border-bottom: 1px solid #f2f2f2;
        background: #ffffff;

        >h3 {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            color: #000;
            margin-bottom: 10px;
            padding: 0 20px 0 30px;
            font-weight: normal;
        }

        >p {
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            font-size: 16px;

            color: #000000;
            font-weight: normal;
            position: relative;
            padding: 0 20px 0 30px;

            &::before {
                position: absolute;
                top: 6px;
                left: 14px;
                display: block;
                content: '';
                width: 8px;
                height: 8px;
                background: #1ac4a8;
                border-radius: 4px;
                z-index: 3;
            }
        }
    }

    &>button {
        &:hover {
            color: #ea4c89;
        }

        cursor: pointer;
        overflow: hidden;
        width: 100%;
        height: 48px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        border: none;
        border-top: 1px solid #f2f2f2;
        border-radius: 0;
        margin: 0;
        padding: 0;

        color: #737373;
        background: none;
    }
}

.notice-list {
    width: 50vw;
    min-width: 400px;

    h2 {
        padding: 20px 6px;
        margin: 0 20px;
        border-bottom: 1px solid #f2f2f2;
        font-size: 14px;
        color: #919191;
        text-align: right;
        font-weight: normal;
    }

    ul {
        height: 45vh;
        box-sizing: border-box;
        background: #ffffff;
        margin: 0 20px;

        li {
            &.readed {
                * {
                    color: #919191 !important;
                }

                >article::before {
                    display: none;
                }
            }

            &:hover {
                background: #f6f6f6;
            }

            cursor: pointer;
            box-sizing: border-box;
            padding: 16px 0;
            line-height: normal;
            width: 100%;
            border-bottom: 1px;
            font-size: 14px;

            border-bottom: 1px solid #f2f2f2;
            background: #ffffff;

            &>h3 {
                display: flex;
                flex-direction: row;
                justify-content: space-between;
                color: #000;
                margin-bottom: 10px;
                padding: 0 20px 0 30px;
            }

            >article {
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
                font-size: 16px;
                color: #000000;
                font-weight: normal;
                position: relative;
                padding: 0 20px 0 30px;

                &::before {
                    position: absolute;
                    top: 6px;
                    left: 14px;
                    display: block;
                    content: '';
                    width: 8px;
                    height: 8px;
                    background: #1ac4a8;
                    border-radius: 4px;
                    z-index: 3;
                }

                &::v-deep * {
                    display: inline !important;
                    white-space: nowrap;
                    font-weight: normal;
                }
            }
        }
    }
}

.notice-detail::v-deep {
    &>.dialog-content>h6 {
        display: none;
    }
}

.notice-detail-close {
    position: absolute;
    right: 0;
    top: 0;
    width: 40px;
    height: 40px;
    z-index: 2;
    line-height: 40px;
    text-align: center;
    font-size: 14px;
    color: #686868;
    font-weight: normal;
    cursor: pointer;
    font-size: 18px;

    &:hover {
        color: #ea4c89;
    }
}

.notice-detail-content {
    width: 50vw;
    min-width: 400px;

    >h2 {
        font-size: 24px;
        padding: 28px 36px 0;
        color: #000000;
        margin-bottom: 18px;
    }

    >h4 {
        font-size: 14px;
        color: #919191;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        font-weight: normal;
        margin: 12px 0 20px;
    }

    >article {
        min-height: 40vh;
        font-size: 16px;
        padding: 24px 36px;
        color: #000000;
        overflow-y: auto;
        margin-bottom: 60px;

        &::v-deep {
            a {
                color: #40c3ec;

                &:visited {
                    color: #40c3ec;
                }
            }
        }
    }

    >footer {
        border-top: 1px solid #ddd;
        line-height: 52px;
        padding: 0 36px;

        span {
            border: none;
            cursor: pointer;
            font-size: 14px;
            padding: 0;
            margin: 0;
            text-decoration: underline;
            height: 16px;
        }
    }
}

@media (max-width: 960px) {
    .header-message {
        .header-message-main {
            position: fixed;
            width: auto;
            left: 15px;
            right: 15px;
            top: 36px;
            padding: 0;
            min-width: auto;
        }
    }

    .notice-list {
        width: 100%;
        min-width: initial;

        h2 {
            text-align: center;
            font-size: 16px;
        }

        ul {
            height: auto;
            overflow: hidden;
            margin: 0 14px;
        }
    }
}
</style>
